package com.lg.partition19;

import java.io.*;
import java.util.StringTokenizer;

/**
 * @author `RKC`
 * @date 2022/4/19 21:44
 */
public class P1833樱花 {

    private static final int M = 1010;
    private static int[] f = new int[M];
    private static int n, m;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        m = get(ss[0], ss[1]);
        n = Integer.parseInt(ss[2]);
        for (int i = 1; i <= n; i++) {
            ss = reader.readLine().split(" ");
            int v = Integer.parseInt(ss[0]), w = Integer.parseInt(ss[1]), cnt = Integer.parseInt(ss[2]);
            if (cnt == 0) {
                for (int j = v; j <= m; j++) f[j] = Math.max(f[j], f[j - v] + w);
                continue;
            }
            for (int k = 1; k <= cnt; k <<= 1) {
                for (int j = m; j >= k * v; j--) {
                    f[j] = Math.max(f[j], f[j - k * v] + k * w);
                }
                cnt -= k;
            }
            if (cnt != 0) {
                for (int j = m; j >= cnt * v; j--) {
                    f[j] = Math.max(f[j], f[j - cnt * v] + cnt * w);
                }
            }
        }
        writer.write(f[m] + "\n");
        writer.flush();
    }

    private static int get(String a, String b) {
        int idx1 = a.indexOf(':'), idx2 = b.indexOf(':');
        int h1 = Integer.parseInt(a.substring(0, idx1)), m1 = Integer.parseInt(a.substring(idx1 + 1));
        int h2 = Integer.parseInt(b.substring(0, idx2)), m2 = Integer.parseInt(b.substring(idx2 + 1));
        return (h2 - h1) * 60 + m2 - m1;
    }
}
